package cn.sylinx.hbatis.ext.mirage.plugin;

import java.util.ArrayList;
import java.util.List;

import cn.sylinx.hbatis.ext.res.ClasspathSqlResourceManager;
import cn.sylinx.hbatis.io.ClasspathResourceScanner;
import cn.sylinx.hbatis.kit.StrKit;
import cn.sylinx.hbatis.log.GLog;
import cn.sylinx.hbatis.plugin.IPlugin;
import cn.sylinx.hbatis.plugin.debug.DebugWrapper;

public class SqlResourcePreloadPlugin implements IPlugin {

	private final static String defaultPath = "sql";

	private List<String> resourcePaths;

	public SqlResourcePreloadPlugin() {
		this(defaultPath);
	}

	public SqlResourcePreloadPlugin(String path) {
		resourcePaths = new ArrayList<>();
		resourcePaths.add(path);
	}

	public SqlResourcePreloadPlugin(List<String> resourcePaths) {
		if (resourcePaths != null) {
			this.resourcePaths = resourcePaths;
		}
	}

	@Override
	public boolean start(Object... objects) {
		load();
		return true;
	}

	@Override
	public boolean stop() {
		ClasspathSqlResourceManager.clear();
		return true;
	}

	private void load() {

		if (DebugWrapper.ME.isDebug()) {
			// 如果是debug模式，则无需预加载到内存
			return;
		}

		if (resourcePaths == null) {
			return;
		}

		resourcePaths.stream().filter(StrKit::isNotBlank).forEach(item -> {

			boolean bl = load(item);
			if (bl) {
				GLog.info("resourcesPath:{} load ok..", item);
			} else {
				GLog.info("resourcesPath:{} load error..", item);
			}
		});
	}

	private boolean load(String resourcesPath) {

		ClasspathResourceScanner crs = new ClasspathResourceScanner(resourcesPath, ".sql");
		List<String> rlist = null;

		try {
			rlist = crs.getResourceNameList();
		} catch (Exception e) {
			GLog.error("resource not found ", e);
			return false;
		}

		if (rlist == null || rlist.isEmpty()) {
			return false;
		}

		for (String r : rlist) {
			ClasspathSqlResourceManager.loadAndGet(r);
			GLog.info("resource:{} loaded ", r);
		}

		return true;

	}

}
